$(document).ready(function () { 

    localStorage.setItem('url',location.href);
    
    $.ajax({
        url: "php/recommend.php",
        data: "data",
        dataType: "json",
        success: function (res) {
            var {data} = res;
            var str = '';
            data.forEach(ele => {
                str += `
                <li class="recommend-list">
                    <a href="details.html?id=${ele.id}">
                        <img src="${ele.img}" alt="${ele.name}">
                        <div class="recommend-name">${ele.name}</div>
                        <div class="recommend-price">${ele.price}</div>
                        <div class="recommend-tips">12.5万人好评</div>
                    </a>
                    <div class="recommend-action">
                        <a href="details.html?id=${ele.id}" class="btn btn-small btn-line-primary">查看详情</a>
                    </div>
                </li>
                `
            });
            $('#J_recommend_cartEmpty .recommend-list').html(str);
        }
    });

    var username = tool.getCookie('username');
    if(username){
        $('#J_siteUserInfo a.login').text('欢迎您'+username);
        $('#J_siteUserInfo a.register').text('退出');
        $('#J_siteUserInfo a.register').attr('href','#');
        $('.login-desc').css('display','none');

        $('#J_siteUserInfo a.register').click(function(){
            tool.removeCookie('username');
            $('.login-desc').css('display','block');
            $('#J_siteUserInfo a.register').attr('href','#');
            $('#J_siteUserInfo a.login').text('登录');
            $('#J_siteUserInfo a.register').text('注册');
            $('#J_siteUserInfo a.register').attr('href','register.html');
            $('.login-desc').next().css('display','block');
            $('.empty-cart-top').show();
            $('.table-cart').hide();
            return false;

        });
        $('.login-desc').next().css('display','none');
        
    }
    
    $('.table-cart').hide();

    var str = localStorage.getItem('cartData');
    if(str){
        $('.empty-cart-top').hide();
        $('.table-cart').show();
        var arr = JSON.parse(str);
        var data = arr.filter(item=>item.username === username);

        if(data.length){
            var ids = arr.map(item=>item.id).join(',');

            $.ajax({
                url:"php/shoppingCar.php",
                data:{ids},
                dataType:"json",
                success(res){
                    var {data} = res;
                    var str = '';
                    for(var i=0;i<data.length;i++){
                        var number = arr.find(item=>item.id === data[i].id).number;
                        var suit = parseInt(arr.find(item=>item.id === data[i].id).suit);
                        str += `
                            <tr>
                                <td><input type="checkbox" name="selectOne"></td>
                                <td><img src="${data[i].img}" width="50" height="50"></td>
                                <td class="name">${data[i].name}</td>
                                <td class="price">单价：￥<span>${data[i].price}</span></td>
                                <td class="number" data-stock="${data[i].stock}">
                                    <button class="btn btn-default reduce">-</button>
                                    <input type="number" name="number" value="${number}">
                                    <button class="btn btn-default add">+</button>
                                </td>
                                <td class="subtotal">小计：￥<span>${data[i].price * number}</span>元</td>
                                <td data-id="${data[i].id}"><button class="remove btn btn-danger">移出购物车</button></td>
                            </tr>
                        `
                    }
                    $('.table-cart table>tbody').html(str);
                    selectAll();
                    selectOne();
                    addAndSub();
                    subtotal();
                    total();
                    removeCart();
                    settlement();
                }
            });
        }
    }


    function selectAll(){
        $('[name="selectAll"]').click(function(){
            $('[name="selectAll"]').prop('checked',$(this).prop('checked'));
            $('[name="selectOne"]').prop('checked',$(this).prop('checked'));
            total();
        });
    }
    function selectOne(){
        $('[name="selectOne"').click(function(){
            var arr = Array.from($('[name="selectOne"'));
            var bool = arr.every(item=> item.checked);
            $('[name="selectAll"').prop('checked',bool);
            total();
        });
    }
    function addAndSub(){
        $('td button.add').click(function(){
            var number = parseInt($(this).prev().val());
            number++;
            if(number>=$(this).parent().attr('data-stock')){
                number = parseInt($(this).parent().attr('data-stock'));
            }
            $(this).prev().val(number);
            var data = JSON.parse(localStorage.getItem('cartData'))
            var id = $(this).parent().siblings().last().attr('data-id')
            var currentData = data.find(item=>item.username === username && item.id == id)
            currentData.number = number;
            localStorage.setItem('cartData',JSON.stringify(data));
            subtotal();
            total();
        });
        $('td button.reduce').click(function(){
            var number = parseInt($(this).next().val());
            number--;
            if(number<=1){
                number=1
            }
            $(this).next().val(number);
            var data = JSON.parse(localStorage.getItem('cartData'))
            var id = $(this).parent().siblings().last().attr('data-id')
            var currentData = data.find(item=>item.username === username && item.id == id)
            currentData.number = number;
            localStorage.setItem('cartData',JSON.stringify(data));
            subtotal();
            total();
        });
    }
    function subtotal(){
        $('tbody .price').each((index,item)=>{
            var price = $(item).children('span').text() - 0;
            var number = $(item).next().children('[name="number"]').val() - 0;
            var sub = price * number;
            $(item).siblings('.subtotal').children('span').text(sub)
        })
    }
    function total(){
        var totalnum = 0
        var totalprice = 0
        $('[name="selectOne"]:checked').each((index,item)=>{
            totalnum += $(item).parent().siblings('.number').children('[name="number"]').val() - 0
            totalprice += $(item).parent().siblings('.subtotal').children('span').text() - 0
        })
        $('.totalnum').text(totalnum);
        $('.totalprice').text(totalprice);
    }
    function removeCart(){
        $('.remove').click(function(){
            var that = this
            layer.confirm('你确定狠心删除吗？',{
                btn:['狠心删除','不舍得']
            },function(){
                $(that).parent().parent().remove()
                var arr = JSON.parse(localStorage.getItem('cartData'))
                var id = $(that).parent().attr('data-id')
                var index = arr.findIndex(item=>item.id == id && item.username === username)
                arr.splice(index,1)
                localStorage.setItem('cartData',JSON.stringify(arr))
                layer.msg('删除成功',{
                    icon:1,
                    time:1500
                })
                arr = JSON.parse(localStorage.getItem('cartData'))
                var data = arr.filter(item=>item.username === username)
                if(!data.length){
                    $('.empty-cart-top').show();
                    $('.table-cart').hide();
                }
            },function(){
                layer.msg('谢谢你对这个商品的偏爱',{
                    icon:1,
                    time:1500
                })
            })
        })
    }
    function settlement(){
        var totalnum = $('.totalnum').val();
        var totalprice = $('.totalprice').val();
        $('td a.btn-success').click(function(){
            if($('tfoot td input').prop('checked') === true){
                layer.msg(`您一共购买${totalnum}件,总结为${totalprice}元,感谢你的购买，期待你的下次来临!`,{
                    icon:1,
                    time:1500
                },function(){
                    localStorage.removeItem('cartData');
                    $('.empty-cart-top').show();
                    $('.table-cart').hide();
                })
            }
            return false;
        });
    }
    
});